<script lang="ts">
import {defineComponent, computed, watch, ref, ComponentInternalInstance} from "vue"
import FormComponent from "@/components/DynamicForm/FormComponent.vue";
import {Ref, UnwrapRef} from "@vue/reactivity";

export default defineComponent({
  name: "ViewForm",
  components: {FormComponent},
  emits: {
    change: (field: string, value: any, rule: any[], fApi: object, setFlag: boolean) => true,
    reload: (instance: ComponentInternalInstance) => true,
    close: (value: any) => true,
    success: (value: any) => true,
    config: (value: any) => true
  },
  props: {
    api: {//接口地址
      type: String,
      required: true
    },
    query: {//请求参数
      type: Object,
      default() {
        return {}
      }
    },
  },
  setup(props, {emit}) {
    /**
     * 表单实例
     */
    const form: Ref<UnwrapRef<any>> = ref(null)

    /**
     * 是否渲染
     */
    const rander = ref(true)

    /**
     * 表单配置
     */
    const option = ref({
      disabled: false,
      inline: false,
      labelPosition: "left",
      labelWidth: "80px"
    })

    /**
     * 请求数据
     */
    const data = computed(() => {
      return {
        api: props.api,
        query: props.query
      }
    })

    /**
     * 监控表单
     */
    watch(() => data, () => {
      rander.value = false
      setTimeout(() => {
        rander.value = true
      }, 10)
    }, {
      deep: true,
      immediate: true
    })

    /**
     * 内部表单配置
     * @param event
     */
    function configLoad(event: any) {
      option.value = event.option.form
    }

    /**
     * 提交表单
     */
    function submitForm() {
      form.value.submitData()
    }

    /**
     * 实例加载完成事件
     * @param event
     */
    function refOnload(event: any) {
      form.value = event
    }


    /**
     * 成功提交事件
     * @param value
     */
    function eventSuccess(value: any) {
      emit('success', value)
    }

    return {
      rander, configLoad, option, submitForm, refOnload, eventSuccess
    }
  }
})
</script>

<template>
  <div v-loading="rander===false">
    <form-component v-if="rander" @success="eventSuccess" :ref="refOnload" @config="configLoad" :api :query/>
    <slot name="footer" :option="option">
      <el-form v-bind="{...option}">
        <el-form-item>
          <el-button @click="submitForm" type="primary" long>保存</el-button>
        </el-form-item>
      </el-form>
    </slot>
  </div>
</template>